package com.csf.controller;

import com.csf.entity.DiscussPost;
import com.csf.entity.Page;
import com.csf.service.CommentService;
import com.csf.service.ElasticSearchService;
import com.csf.service.UserService;
import com.csf.service.likeService;
import com.csf.util.CommunityActivation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class SearchController implements CommunityActivation{

    @Autowired
    private ElasticSearchService elasticSearchService;

    @Autowired
    private UserService userService;

    @Autowired
    private likeService likeService;


    @RequestMapping(path = "/searchDisES",method = RequestMethod.GET)
    public String getSearch(String keyWord, Page page, Model model){
//        获取符合条件的帖子
        org.springframework.data.domain.Page<DiscussPost> disPage =
    elasticSearchService.findDiscussPostEs(keyWord, page.getCurrent()-1, page.getLimit());
        List<Map<String,Object>> mapList = new ArrayList<>();
        if (disPage != null){
            for (DiscussPost post : disPage) {
                Map<String,Object> map = new HashMap<>();
                map.put("post",post);
                map.put("user",userService.findUserById(post.getUserId()));
                int likeCount = likeService.likeCount(ENTITY_TYPE_POST, post.getId());
                map.put("likeCount",likeCount);
                mapList.add(map);
            }
            model.addAttribute("disMap",mapList);
            model.addAttribute("keyWord",keyWord);
        }
        page.setPath("/searchDisES?keyWord="+keyWord);
        page.setRows(disPage ==null?0: (int)disPage.getTotalElements());
        return "/site/search";
    }

}
